package uk.co.wobblycogs.vegas;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Graham Smith
 */
public class SettingsFactory {

	private static volatile SettingsFactory instance;
	private static final Logger logger = LoggerFactory.getLogger(SettingsFactory.class);
	private Properties settings;

	private SettingsFactory() {
	}

	public static SettingsFactory getInstance() {
		//double-checked lock - safe from Java 5 onwards.
		if (instance == null) {
			synchronized (SettingsFactory.class) {
				if (instance == null) {
					instance = new SettingsFactory();
				}
			}
		}
		return instance;
	}

	/**
	 * Determines if the system can find a valid settings file.
	 *
	 * @return true if the expected settings file is available and can be read.
	 */
	public boolean isAvailable() {
		return Files.isReadable(getSettingsPath());
	}

	/**
	 * Provides a number of system settings such as database connection
	 * settings. If the settings file can not be found null is returned.
	 * Typically this method shouldn't be called without first calling
	 * isAvailable.
	 *
	 * @return a {@code Properties} containing settings or null if the settings
	 * can't be found.
	 * @throws IOException if the settings can't be loaded.
	 */
	public Properties getSettings() throws IOException {
		if (settings == null) {
			synchronized (this) {
				if (settings == null) {
					if (isAvailable()) {
						settings = new Properties();
						try (InputStream settingsStream = new FileInputStream(getSettingsPath().toFile())) {

//							if (settingsFile.exists()) {
//								logger.info("Found settings file: {}", settingsFile.getPath());
//								settingsStream = new FileInputStream(settingsFile);
//							} else {
//								logger.info("Didn't file settings file so loading default internal settings.");
//								settingsStream = SettingsFactory.class.getResourceAsStream("/META-INF/settings.properties");
//							}
							settings.load(settingsStream);
						}
					}
				}
			}
		}

		return settings;
	}

	/**
	 * Provides a file that should point to the settings.
	 *
	 * @return
	 */
	public Path getSettingsPath() {
		Path userDir = Paths.get(System.getProperty("user.dir"));
		Path settingsFile = userDir.resolve("settings.properties");
		logger.info("Using settings file: {}", settingsFile);
		return settingsFile;
	}
}
